<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\DrainageLink\Action\Operation;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ChannelCode\Contract\ChannelCodeContract;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkClickContract;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkContract;
use MoChat\Plugin\RoomAutoPull\Contract\WorkRoomAutoPullContract;

/**
 * 引流链接H5- 获取二维码.
 *
 * Class ContactData.
 * @Controller
 */
class GetQRCode extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var DrainageLinkContract
     */
    protected $drainageLink;

    /**
     * @Inject
     * @var ChannelCodeContract
     */
    protected $channelCode;

    /**
     * @Inject
     * @var WorkRoomAutoPullContract
     */
    protected $workRoomAutoPull;

    /**
     * @Inject
     * @var DrainageLinkClickContract
     */
    protected $drainageLinkClick;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/operation/drainageLink/getQRCode", methods="get")
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 接收参数
        $params = [
            'id' => (int) $this->request->input('id', 1),
        ];
        // 参数验证
        $this->validated($params);

        // 查询数据
        $link = $this->drainageLink->getDrainageLinkById($params['id'], ['id', 'type', 'qrcode_type', 'qrcode', 'qrcode_id', 'page_title', 'corp_name', 'corp_logo', 'corp_mobile_status', 'corp_mobile', 'corp_nickname_status', 'corp_nickname', 'corp_avatar', 'guide_text', 'is_login']);
        if (empty($link)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未找到该链接');
        }
        // 点击统计，转移到/operation/drainageLink/getScheme
//        $this->createDrainageLinkClick($params);
        if ($link['type'] === 1) {
            return $this->getPersonal($link);
        }
        if ($link['type'] === 2) {
            return $this->getRoom($link);
        }

        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'id' => 'required | integer | min:0 | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'id.required' => '链接ID 必填',
            'id.integer' => '链接ID 必需为整数',
            'id.min' => '链接ID 不可小于1',
        ];
    }

    private function getPersonal($link)
    {
        // 个人微信二维码方式，则禁用企业logo、电话、展示企业头像、昵称功能
        if ($link['qrcodeType'] === 1) {
            $link['qrcode'] = file_full_url($link['qrcode']);
            $link['corpLogo'] = '';
            if (! empty($link['corpAvatar'])) {
                $link['corpAvatar'] = file_full_url($link['corpAvatar']);
            }
        }
        if ($link['qrcodeType'] === 2) {
            $channelCode = $this->channelCode->getChannelCodeById($link['qrcodeId'], ['qrcode_url']);
            $link['qrcode'] = file_full_url($channelCode['qrcodeUrl']);
            $link['corpLogo'] = file_full_url($link['corpLogo']);
            if (! empty($link['corpAvatar'])) {
                $link['corpAvatar'] = file_full_url($link['corpAvatar']);
            }
        }
        // corpMobileStatus是新增字段，前端并无判断，后端添加
        if ($link['corpMobileStatus'] === 0) {
            $link['corpLogo'] = '';
            $link['corpMobile'] = '';
            $link['corpAvatar'] = '';
            $link['corpNickname'] = '';
        }

        return $link;
    }

    private function getRoom($link)
    {
        if ($link['qrcodeType'] === 1) {
            $link['qrcode'] = file_full_url($link['qrcode']);
        }
        if ($link['qrcodeType'] === 2) {
            $workRoomAutoPull = $this->workRoomAutoPull->getWorkRoomAutoPullById($link['qrcodeId'], ['qrcode_url']);
            $link['qrcode'] = file_full_url($workRoomAutoPull['qrcodeUrl']);
        }
        $link['corpLogo'] = file_full_url($link['corpLogo']);
        if (! empty($link['corpAvatar'])) {
            $link['corpAvatar'] = file_full_url($link['corpAvatar']);
        }
        return $link;
    }

    /**
     * 点击统计
     */
    private function createDrainageLinkClick(array $params): array
    {
        // 数据操作
        Db::beginTransaction();
        try {
            // 创建点击记录
            $data = [
                'link_id' => $params['id'],
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $this->drainageLinkClick->createDrainageLinkClick($data);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '链接点击统计失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
        return [];
    }
}
